import '../user_model.dart';

/// 登录响应模型
class LoginResponse {
  /// 访问令牌
  final String accessToken;
  
  /// 刷新令牌
  final String? refreshToken;
  
  /// 令牌类型
  final String tokenType;
  
  /// 令牌过期时间（秒）
  final int expiresIn;
  
  /// 用户信息
  final UserModel? user;
  
  /// 构造函数
  LoginResponse({
    required this.accessToken,
    this.refreshToken,
    this.tokenType = 'Bearer',
    required this.expiresIn,
    this.user,
  });
  
  /// 从JSON创建登录响应
  factory LoginResponse.fromJson(Map<String, dynamic> json) {
    return LoginResponse(
      accessToken: json['access_token'] as String,
      refreshToken: json['refresh_token'] as String?,
      tokenType: json['token_type'] as String? ?? 'Bearer',
      expiresIn: json['expires_in'] as int? ?? 3600,
      user: json['user'] != null
          ? UserModel.fromJson(json['user'] as Map<String, dynamic>)
          : null,
    );
  }
  
  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'access_token': accessToken,
      if (refreshToken != null) 'refresh_token': refreshToken,
      'token_type': tokenType,
      'expires_in': expiresIn,
      if (user != null) 'user': user!.toJson(),
    };
  }
  
  /// 计算令牌过期时间
  DateTime getExpirationTime() {
    return DateTime.now().add(Duration(seconds: expiresIn));
  }
  
  /// 检查令牌是否过期
  bool isTokenExpired() {
    // 如果当前时间超过过期时间，则令牌已过期
    return DateTime.now().isAfter(getExpirationTime());
  }
  
  /// 创建一个新的登录响应，复制原有属性并覆盖指定属性
  LoginResponse copyWith({
    String? accessToken,
    String? refreshToken,
    String? tokenType,
    int? expiresIn,
    UserModel? user,
  }) {
    return LoginResponse(
      accessToken: accessToken ?? this.accessToken,
      refreshToken: refreshToken ?? this.refreshToken,
      tokenType: tokenType ?? this.tokenType,
      expiresIn: expiresIn ?? this.expiresIn,
      user: user ?? this.user,
    );
  }
} 